package cn.bonoon.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import cn.bonoon.core.plugins.AnnouncementService;
import cn.bonoon.entities.plugins.AnnouncementEntity;
import cn.bonoon.kernel.menus.ChannelInfo;
import cn.bonoon.kernel.menus.IModuleInfo;
import cn.bonoon.kernel.menus.IStyleGetter;
import cn.bonoon.kernel.menus.MenuInfo;
import cn.bonoon.kernel.menus.ModuleManager;
import cn.bonoon.kernel.menus.PartInfo;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.security.PrivilegeChecker;
import cn.bonoon.kernel.support.services.UserService;
import cn.bonoon.kernel.util.MD5Util;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.controllers.AbstractController;
import cn.bonoon.kernel.web.models.JsonResult;
import cn.bonoon.kernel.web.models.LayoutModel;
import cn.bonoon.util.UrlKeyHelper;

/**
 * <pre>
 * 系统的首页和各个子系统的首页的定义
 * 
 * 系统首页的访问路径的规则，以"/"开头为系统首页的路径
 * 
 * </pre>
 * @author jackson
 *
 */
@Controller
@RequestMapping("s")
public class HostController extends AbstractController{
	
	private final static int MAX_SIZE = 7;
	
	@Autowired
	private ModuleManager moduleManager;
	
	@Autowired
	private UserService userService;
	
	@Value("${account.force.check.password}")
	private boolean forceCheckPassword;
	
	private String errPicSrc;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		errPicSrc = toUrl("/res/images/subsystem.png");
	}
	
	private LayoutModel build(String mid, HttpServletRequest request, String title, IStyleGetter styleGetter, LogonUser user){
		LayoutModel layout = new LayoutModel(mid, request, moduleManager.getEndpoint());
		layout.initLayout(title, styleGetter);

		//是否需要强制修改密码
		if(forceCheckPassword && user.needChangePwd()){
			layout.addBlock("openDialog('" + toUrl("/s/user/change/pwd/forced.do") + "');");
		}
		return layout;
	}
	
	//子系统
	@RequestMapping(value = "{key}!sys.do")
	public ModelAndView module(HttpServletRequest request, @PathVariable("key") String key){
		try{
			LogonUser user = getUser();
			if(!user.allowAccess()){
				return new ModelAndView(new RedirectView(moduleManager.getDefaultEndpoint()));
			}
			
			IModuleInfo module = moduleManager.module(key);
			if(null == module){
				//异常
				throw new Exception("要访问的子系统不存在！");
			}
			PrivilegeChecker privilege = userService.privilege(user, module);
			LayoutModel layout = build(key, request, "首页", module, user);
			
			layout.buildChannel(module, user, privilege, null);
			
			//添加用户定义的快捷菜单
			//不一定有菜单
			StringBuilder subsystemmain = new StringBuilder();
			
			ModelAndView mav = _get(layout, module, user, subsystemmain);
			
//			subsystemmain.append("<div data-settings=\"iconClassname:'icon-sys'\" title='快捷菜单'>");
//			_buildShortcutMenu(layout, subsystemmain, userService.shortcutMenus(user, module.getId()));
//			layout.addObject("shortcutMenuType", 1);
//			subsystemmain.append("</div>");
			
			
			return mav;
		}catch(Throwable ex){
			return errorPanel(ex);
		}
	}
	
	//登录
	@RequestMapping
	public ModelAndView get(HttpServletRequest request){
		try{
			LogonUser user = getUser();
			if(!user.allowAccess()){
				return new ModelAndView(new RedirectView(moduleManager.getDefaultEndpoint()));
			}
			IModuleInfo mi = moduleManager.module();
			
			LayoutModel layout = build(mi.getId(), request, "首页", moduleManager, user);
			PrivilegeChecker privilege = userService.privilege(user, mi);
			layout.buildChannel(mi, user, privilege, null);
			
			StringBuilder hostmain = new StringBuilder("<div data-settings=\"iconClassname:'icon-sys'\" title='子系统'><table style='width:100%' cellpadding='15' cellspacing='0'><tr>");
			
			int i = 1;
			if(user.isSuper()){
				for(IModuleInfo module : moduleManager.modules()){
					i = _parse(i, hostmain, module, errPicSrc);
				}
			}else{
				for(String key : userService.accessableModules(user)){
					IModuleInfo module = moduleManager.module(key);
					if(null != module){
						i = _parse(i, hostmain, module, errPicSrc);
					}
				}
			}
			
			for(; i <= MAX_SIZE; i++){
				hostmain.append("<td></td>");
			}
			hostmain.append("<td></td></tr></table><hr style='width:90%;'/>");
			
			// 2.添加用户定义的跨子系统的快捷菜单
//			_buildShortcutMenu(layout, hostmain, userService.shortcutMenus(user, mi.getId()));
//			layout.addObject("shortcutMenuType", 0); // 返回系统类型(0:系统; 1:子系统;)，用于设置菜单项 disableItem 属性
		
			// 返回界面，显示不同标题图片
//			layout.addObject("userName", user.getUsername());
//			layout.addObject("moduleName", mi.getName());
			
			return _get(layout, mi, user, hostmain.append("</div>"));
		}catch(Throwable ex){
			return errorPanel(ex);
		}
	}
	
//	private void _buildShortcutMenu(LayoutModel layout, StringBuilder sb, List<ShortcutMenuEntity> smenu){
//		if(null != smenu){
//			sb.append("<div id='loader'></div><div id='module_list'>");
//			for (ShortcutMenuEntity menu : smenu) {
//				IShortcutInfo item = moduleManager.shortcut(menu.getMenuId());
//				if (null != item) {//需要根据用户的权限来过滤快捷菜单
//					String name = menu.getName();
//					String iconCls = item.getIconCls();
//					String img_src = StringHelper.isNotEmpty(iconCls) ? iconCls : "/res/images/shortcuts_32.png";
//					if (StringHelper.isEmpty(name)) name = item.getName(); // 没有自定义菜单名称
//					sb.append("<div class='modules'><a href='").append(item.getHref());
//					sb.append("'><img width='32px' onerror=\"this.onerror=null;this.src='/res/images/shortcuts_32.png'\" src='").append(img_src).append("'/></a><p><a href='");
//					sb.append(item.getHref()).append("'>").append(name).append("</a><input type='hidden' class='menuId' value='").append(menu.getId()).append("'/></p></div>");
//				}
//			}
//			sb.append("<div class='clear'></div></div>");
//		}
//	}
	
	// 位于左边的快捷菜单，已放弃
//	private void buildLayout(LayoutModel layout, List<ShortcutMenuEntity> smenu){
//		if(null != smenu){
//			StringBuilder shortcutMenus = layout.menuBuilder();
//			for (ShortcutMenuEntity menu : smenu) {
//				MenuInfo item = moduleManager.menu(menu.getMenuId());
//				if(null != item){
//					String name = menu.getName();
//					if(StringHelper.isEmpty(name)) name = item.getName();//没有自定义菜单名称
//					shortcutMenus.append("<li iconCls='icon-menu'><span><a id='").append(menu.getId())
//						.append("' href='").append(item.getHref())
//						.append("'>").append(name).append("</a></span></li>");
//				}
//			}
//			//菜单的ContextMenu事件,菜单的操作项有：
//			//1.删除快捷菜单
//			//2.重命名快捷菜单
//			//TODO 未处理完成
//			layout.menuContextMenu(
//				new ContextMenuItem("重命名", "alert('重命名');"),
//				new ContextMenuItem("排序", "alert('排序');"),
//				new ContextMenuItem("设为系统菜单", "alert('设为系统菜单');"),
//				new ContextMenuItem("设为子系统菜单", "alert('设为子系统菜单');"),
//				new ContextMenuItem("删除快捷菜单", "alert('删除快捷菜单');")
//			);
//		}
//	}

	private ModelAndView _get(LayoutModel layout, IModuleInfo mi, LogonUser user, StringBuilder hostmain){
		for(PartInfo part : mi.getParts()){
			if(part.checked(user)){
				hostmain.append("<div title='").append(part.getName()).append("'");
				if(StringHelper.isNotEmpty(part.getIconCls())){
					hostmain.append("data-settings=\"iconClassname:'").append(part.getIconCls()).append("'\"");
				}
				hostmain.append(" href='").append(part.getUrl()).append("'></div>");
			}
		}
		String key = mi.getId();
		layout.addObject("hostmain", hostmain).addObject("key", UrlKeyHelper.filter(key));
		layout.addObject("content", _buildContent(announcementService.byKey(key)));
		return layout.execute("sys/sys-index");
	}

	@Autowired
	private AnnouncementService announcementService;
	private final String id = MD5Util.randomMD5String();
	
	private StringBuilder _buildContent(List<AnnouncementEntity> announcement) {
		StringBuilder sb = new StringBuilder();
		for (AnnouncementEntity entity : announcement) {
			sb.append("<tr><td style='padding-top:10px;'><font style='line-height:150%;'>")
				.append(entity.getContent())
				.append("</font></td></tr><tr><td style='padding-bottom:10px;border:solid #e6e6e6;border-width:0px 0px 1px 0px;'><font style='line-height:150%;'>")
				.append(StringHelper.datetime2String(entity.getCreateAt())).append("</font></td></tr>");
		}
		return sb;
	}

	@RequestMapping("{key}!announcement.dlg")
	public String dlg(Model model, @PathVariable("key") String key) {
		model.addAttribute("id", id);
		model.addAttribute("attrs", "title='公告' style='width:700px;height:500px;'");
		model.addAttribute("content", _buildContent(announcementService.byKey(key, 0)));
		model.addAttribute("key", UrlKeyHelper.filter(key));
		return "/sys/sys-announcement-dlg";
	}

	@ResponseBody
	@RequestMapping(value = "{key}!announcement.load", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult load(int page, @PathVariable("key") String key) {
		try{
			return JsonResult.result(_buildContent(announcementService.byKey(key, page)).toString());
		}catch(Exception ex){
			return JsonResult.result(ex);
		}
	}
	
	//菜单的点击事件t
	private static final String click = "var menuTitle = this.title;" +
			"if(jQuery('#tabs-sys-settings-management').buptab('exists', menuTitle)){" +
			"jQuery('#tabs-sys-settings-management').buptab('select', menuTitle);}else{" +
			"var content = '<iframe scrolling=\"auto\" frameborder=\"0\" src=\"'+this.href+'\" style=\"width:100%;height:100%;\"></iframe>';" +
			"jQuery('#tabs-sys-settings-management').buptab('add', {content:content,title:menuTitle,closable:true});}return false;";
	
	@RequestMapping("user/{key}!settings.do")
	public ModelAndView settings(HttpServletRequest request, @PathVariable("key") String key){
		return __settings(request, key);
	}
	
	@RequestMapping("user/settings.do")
	public ModelAndView settings(HttpServletRequest request){
		return __settings(request, "info");
	}
	
	private ModelAndView __settings(HttpServletRequest request, String key){
		try{
			LogonUser user = getUser();
			
			PrivilegeChecker privilege = userService.privilege(user, moduleManager.module().getId(), moduleManager.getChannelManager().getId());
			ChannelInfo personalCenter = moduleManager.personalCenter();			
			LayoutModel layout = build(key, request, personalCenter.navigation(), moduleManager, user);
			layout.buildChannel(personalCenter.getModule(), user, privilege, personalCenter.getId());

			StringBuilder menus = layout.menuBuilder();
			MenuInfo selected = null;
			List<MenuInfo> items = personalCenter.getMenus();
			if(StringHelper.isEmpty(key)){
				key = items.get(0).getKey();
			}
			for(MenuInfo item : items){
				//TODO 这里需要进行操作权限的限制
				menus.append("<li><span>");
				if(key.equals(item.getKey())){
					item.button(menus, "menuSelected");
					selected = item;
				}else{
					item.button(menus, "");
				}
				menus.append("</span></li>");
			}
			layout.setMenuOnClick(click);
			if(null != selected){
				StringBuilder block = layout.getBlock();
				block.append("jQuery('#tabs-sys-settings-management').buptab('add', {content:'<iframe scrolling=\"auto\" frameborder=\"0\" src=\"");
				block.append(selected.getHref()).append("\" style=\"width:100%;height:100%;\"></iframe>',title:'").append(selected.getName()).append("'});");
			}
			return layout.execute("sys/sys-settings-management");
		}catch(Throwable ex){
			return errorPanel(ex);
		}
	}
	
	private int _parse(int i, StringBuilder html, IModuleInfo mi, String errSrc) {
		html.append(
				"<td style='width:100px;' valign='top' align='center'><a href='")
				.append(mi.getEndpoint()).append("'><img width='44px' src='")
				.append(mi.getThumbnail())
				.append("' onerror=\"this.onerror=null;this.src='")
				.append(errSrc).append("'\"/></a><p><a href='")
				.append(mi.getEndpoint()).append("'>").append(mi.getName())
				.append("</a></p>");
		if (i < MAX_SIZE) {
			return i + 1;
		} else {
			html.append("<td></td><tr></tr>");
		}
		return 1;
	}
}
